package org.gap.wizards.views;

import net.slashie.libjcsi.CSIColor;
import net.slashie.libjcsi.CharKey;
import net.slashie.libjcsi.ConsoleSystemInterface;
import net.slashie.libjcsi.textcomponents.MenuBox;

import org.gap.wizards.pc.SpellBook;
import org.gap.wizards.spells.Spell;

public class LibJCsiSelectSpellView implements View, SpellSelectionView {
	private final ViewPlatform console;
	private MenuBox<Spell> menuBox;

	public LibJCsiSelectSpellView(ConsoleSystemInterface csi, ViewPlatform console) {
		this.console = console;
		menuBox = new MenuBox<Spell>(csi, MenuBox.MultiSelect);
		menuBox.setBounds(80, 1, 36, 36);
		menuBox.setBorderColor(CSIColor.BLUE);
		menuBox.setBorder(true);
	}
	
	@Override
	public void setItems(SpellBook spells) {
		menuBox.setMenuItems(spells.getAll());
	}
	
	@Override
	public Spell getSelection() {
		console.saveBuffer();
		CharKey keyPressed = null;
		do {
			draw();
			keyPressed = console.getKeyPressed();
			if (keyPressed.code == CharKey.j) {
				menuBox.moveDown();
			} else if (keyPressed.code == CharKey.k) {
				menuBox.moveUp();
			} else if (keyPressed.code == CharKey.SPACE) {
				menuBox.selectCursor();
			}
		} while (keyPressed.code != CharKey.ENTER);
		
		if (menuBox.getSelected().isEmpty()) {
			return menuBox.getItemAtCursor();
		}
		console.restore();
		console.refresh();
		return menuBox.getSelected().get(0);
	}

	@Override
	public void draw() {
		menuBox.draw();
	}
}
